<template>
  <div class="users-manage">
    <div class="table-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="userList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="role" label="角色">
        <template #default="{ row }">
          <el-tag :type="getRoleType(row.role)">{{ getRoleLabel(row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isConsultant" label="咨询师">
        <template #default="{ row }">
          <el-switch
            v-model="row.isConsultant"
            :active-value="1"
            :inactive-value="0"
            :disabled="row.role !== 'EXPERT'"
            :before-change="() => handleConsultantBeforeChange(row)"
          />
          <el-tooltip
            v-if="row.role !== 'EXPERT'"
            content="只有专家角色可以设置为咨询师"
            placement="top"
          >
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="specialty" label="专长领域" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" style="width: 100%">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="专家" value="EXPERT" />
            <el-option label="家长" value="PARENT" />
            <el-option label="儿童" value="CHILD" />
          </el-select>
        </el-form-item>
        <el-form-item label="专长领域" prop="specialty" v-if="form.isConsultant === 1">
          <el-input v-model="form.specialty" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction" v-if="form.isConsultant === 1">
          <el-input v-model="form.introduction" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 咨询师信息弹窗 -->
    <el-dialog
      v-model="consultantDialogVisible"
      title="设置咨询师信息"
      width="500px"
    >
      <el-form
        ref="consultantFormRef"
        :model="consultantForm"
        :rules="consultantRules"
        label-width="80px"
      >
        <el-form-item label="专长领域" prop="specialty">
          <el-input v-model="consultantForm.specialty" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="个人简介" prop="introduction">
          <el-input v-model="consultantForm.introduction" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleConsultantCancel">取消</el-button>
        <el-button type="primary" @click="handleConsultantSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, InfoFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({})

const consultantDialogVisible = ref(false)
const consultantFormRef = ref(null)
const consultantForm = ref({
  id: null,
  specialty: '',
  introduction: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  specialty: [
    { required: true, message: '请输入专长领域', trigger: 'blur', validator: (rule, value, callback) => {
      if (form.value.isConsultant === 1 && !value) {
        callback(new Error('请输入专长领域'))
      } else {
        callback()
      }
    }}
  ],
  introduction: [
    { required: true, message: '请输入个人简介', trigger: 'blur', validator: (rule, value, callback) => {
      if (form.value.isConsultant === 1 && !value) {
        callback(new Error('请输入个人简介'))
      } else {
        callback()
      }
    }}
  ]
}

const consultantRules = {
  specialty: [
    { required: true, message: '请输入专长领域', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入个人简介', trigger: 'blur' }
  ]
}

const getRoleType = (role) => {
  const types = {
    ADMIN: 'danger',
    EXPERT: 'warning',
    PARENT: 'success',
    CHILD: 'info'
  }
  return types[role] || 'info'
}

const getRoleLabel = (role) => {
  const labels = {
    ADMIN: '管理员',
    EXPERT: '专家',
    PARENT: '家长',
    CHILD: '儿童'
  }
  return labels[role] || role
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await request.get('admin/user/list', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value
      }
    })
    userList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    username: '',
    password: '',
    role: '',
    status: 1,
    isConsultant: 0,
    specialty: '',
    introduction: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    await request.delete(`/api/admin/user/${row.id}`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    await request.put(`/admin/user/${row.id}/status`, {
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const handleConsultantBeforeChange = async (row) => {
  if (row.role !== 'EXPERT') {
    ElMessage.warning('只有专家角色可以设置为咨询师')
    return false
  }

  if (!row.isConsultant) {
    // 要设置为咨询师
    consultantForm.value = {
      id: row.id,
      specialty: row.specialty || '',
      introduction: row.introduction || ''
    }
    consultantDialogVisible.value = true
    return false
  } else {
    // 取消咨询师身份
    try {
      await request.put(`/admin/user/${row.id}/consultant`, {
        isConsultant: 0,
        specialty: '',
        introduction: ''
      })
      ElMessage.success('已取消咨询师身份')
      await fetchUsers()
      return true
    } catch (error) {
      ElMessage.error('操作失败')
      return false
    }
  }
}

const handleConsultantCancel = () => {
  const userId = consultantForm.value.id
  const user = userList.value.find(u => u.id === userId)
  if (user) {
    user.isConsultant = 0
  }
  consultantDialogVisible.value = false
  consultantForm.value = {
    id: null,
    specialty: '',
    introduction: ''
  }
}

const handleConsultantSubmit = async () => {
  if (!consultantFormRef.value) return

  await consultantFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await request.put(`/admin/user/${consultantForm.value.id}/consultant`, {
          isConsultant: 1,
          specialty: consultantForm.value.specialty,
          introduction: consultantForm.value.introduction
        })
        ElMessage.success('咨询师信息设置成功')
        consultantDialogVisible.value = false
        fetchUsers()
      } catch (error) {
        const user = userList.value.find(u => u.id === consultantForm.value.id)
        if (user) {
          user.isConsultant = 0
        }
        ElMessage.error('设置失败')
      }
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await request.post('/admin/user', form.value)
          ElMessage.success('添加成功')
        } else {
          await request.put(`/api/admin/user/${form.value.id}`, form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchUsers()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.users-manage {
  padding: 20px;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.info-icon {
  margin-left: 5px;
  color: #909399;
  cursor: help;
}
</style>